package br.com.actionsystem.gdp.telas;

import br.com.actionsystem.gdp.dao.IntReservasDao;
import br.com.actionsystem.gdp.dao.ReservaDao;
import br.com.actionsystem.gdp.modelo.Reservas;
import br.com.actionsystem.gdp.util.DaoException;
import br.com.actionsystem.gdp.util.LayoutHelp;
import br.com.actionsystem.gdp.util.TableModelReservas;
import br.com.actionsystem.gdp.util.TextNumber;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.text.NumberFormatter;

public class JfmReservas extends AbstratcTelas {

    DecimalFormat formatoDecimal = new DecimalFormat("###,###,##0.00");
    private JTextField nome = null;
    private JTextField conta = null;
    private JTextField agencia = null;
    private JFormattedTextField saldo = null;
    private JFormattedTextField limite = null;
    private JTable tabela = null;
    private JScrollPane rolarTela = new JScrollPane();
    IntReservasDao dao = new ReservaDao();
    Reservas reserva = new Reservas();
    List<Reservas> lista = null;

    public JfmReservas() {
        super("Reservas");
        iniciar();
        acoesDosBotoes();
        Dimension dimensao = new Dimension(590, 400);
        setSize(dimensao);
        setDefaultCloseOperation(JfmReservas.HIDE_ON_CLOSE);


    }

    public void iniciar() {
        JPanel principal = new JPanel();
        principal.setLayout(new GridBagLayout());
        principal.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        getCabecalhoPn().add(new JLabel("Nome *"), LayoutHelp.addLabel());
        getCabecalhoPn().add(getNome(), LayoutHelp.addComponent4());

        getCabecalhoPn().add(new JLabel("Conta"), LayoutHelp.addLabel());
        getCabecalhoPn().add(getConta(), LayoutHelp.addComponentFinal());

        getCabecalhoPn().add(new JLabel("Agência"), LayoutHelp.addLabel());
        getCabecalhoPn().add(getAgencia(), LayoutHelp.addComponent1());

        getCabecalhoPn().add(new JLabel("Saldo *"), LayoutHelp.addLabel());
        getCabecalhoPn().add(getSaldo(), LayoutHelp.addComponent2());

        getCabecalhoPn().add(new JLabel("Limite"), LayoutHelp.addLabel());
        getCabecalhoPn().add(getLimite(), LayoutHelp.addComponentFinal());

        Dimension dimensao = new Dimension(110, 27);
        for (int i = 0; i < getCabecalhoPn().getComponentCount(); i++) {
            JComponent componente = (JComponent) getCabecalhoPn().getComponent(i);
            if (!(componente instanceof JLabel)) {
                getCabecalhoPn().getComponent(i).setMinimumSize(dimensao);
                getCabecalhoPn().getComponent(i).setPreferredSize(dimensao);
            }
            componente.setFont(fontBond);
        }
        getCabecalhoPn().add(new JLabel(), LayoutHelp.addComponentFinal());
        getCabecalhoPn().add(getBotaoPn(), LayoutHelp.addComponentFinal());
        principal.add(getCabecalhoPn(), LayoutHelp.addComponentFinal());
        rolarTela.setViewportView(createJTable());
        rolarTela.setMinimumSize(new Dimension(400, 200));
        rolarTela.setPreferredSize(new Dimension(400, 200));
        principal.add(rolarTela, LayoutHelp.addComponentFinal());
        getContentPane().add(principal);


    }

    private void atualizaTabela() {
        lista = dao.listaTodas();
        TableModelReservas model = new TableModelReservas(lista);
        tabela.setModel(model);
        rolarTela.repaint();
    }

    public void acoesDosBotoes() {
        getSalvarBt().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                carregaReservas();
                try {
                    if (!ValidaCampos()) {
                        return;
                    }
                    dao.salvar(reserva);
                    atualizaTabela();
                    limparTela();
                    reserva = new Reservas();
                } catch (Exception ex) {
                    ex.printStackTrace();

                }
            }
        });

        getNovoBt().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                limparTela();
                reserva = new Reservas();
            }
        });


        getExcluir().addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (reserva == null || reserva.getIdReservas() == 0) {
                    JOptionPane.showMessageDialog(null, "Selecione uma reserva para poder excluir.");
                    return;
                }
                Object opcoes[] = {"Sim", "Não"};
                int op = JOptionPane.showInternalOptionDialog(JfmReservas.this,
                        "Você tem certeza que quer apagar essa reserva ? tem certeza mesmo?", "Aviso",
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opcoes, null);
                if (op == 0) {
                    try {
                        dao.delete(reserva);
                        reserva = new Reservas();
                        limparTela();
                        atualizaTabela();
                    } catch (DaoException ex) {
                        JOptionPane.showMessageDialog(null, ex.getMessage());
                        ex.printStackTrace();
                    }

                }

            }
        });


    }

    public JTable createJTable() {
        lista = dao.listaTodas();
        TableModelReservas model = new TableModelReservas(lista);
        tabela = new JTable(model);
        tabela.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tabela.setAutoscrolls(true);
        tabela.getColumnModel().getColumn(0).setPreferredWidth(120);
        tabela.getColumnModel().getColumn(1).setPreferredWidth(80);
        tabela.getColumnModel().getColumn(2).setPreferredWidth(80);
        tabela.getColumnModel().getColumn(3).setPreferredWidth(80);

        tabela.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                int row = tabela.getSelectedRow();
                reserva = lista.get(row);
                descarregaReservas();
            }
        });

        return tabela;
    }

    private JFormattedTextField setValor(JFormattedTextField valor) {


        NumberFormatter formatoNumerico = new NumberFormatter(formatoDecimal) {

            @Override
            public Object stringToValue(String text) throws ParseException {
                if (text.equals("0,00") || text.equals("0.00") || text.equals("")) {
                    return null;
                } else {
                    return super.stringToValue(text);
                }
            }
        };
        formatoNumerico.setAllowsInvalid(true);
        valor = new JFormattedTextField(formatoNumerico);
        valor.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        return valor;
    }

    public Reservas getReserva() {
        return reserva;
    }

    public void setReserva(Reservas reserva) {
        this.reserva = reserva;
    }

    public JScrollPane getRolarTela() {
        return rolarTela;
    }

    public void setRolarTela(JScrollPane rolarTela) {
        this.rolarTela = rolarTela;
    }

    public JTable getTabela() {
        return tabela;
    }

    public JFormattedTextField getLimite() {
        if (limite == null) {
            DecimalFormat formatoDecimal = new DecimalFormat("###,###,##0.00");
            NumberFormatter formatoNumerico = new NumberFormatter(formatoDecimal) {

                @Override
                public Object stringToValue(String text) throws ParseException {
                    if (text.equals("0,00") || text.equals("0.00") || text.equals("")) {
                        return null;
                    } else {
                        return super.stringToValue(text);
                    }
                }
            };
            formatoNumerico.setAllowsInvalid(true);
            limite = new JFormattedTextField(formatoNumerico);
            limite.setHorizontalAlignment(javax.swing.JTextField.RIGHT);

        }
        return limite;
    }

    public JFormattedTextField getSaldo() {
        if (saldo == null) {
            DecimalFormat formatoDecimal = new DecimalFormat("###,###,##0.00");
            NumberFormatter formatoNumerico = new NumberFormatter(formatoDecimal) {

                @Override
                public Object stringToValue(String text) throws ParseException {
                    if (text.equals("0,00") || text.equals("0.00") || text.equals("")) {
                        return null;
                    } else {
                        return super.stringToValue(text);
                    }
                }
            };
            formatoNumerico.setAllowsInvalid(true);
            saldo = new JFormattedTextField(formatoNumerico);
            saldo.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
            saldo.setDocument(new TextNumber());
        }
        return saldo;
    }

    public JTextField getAgencia() {
        if (agencia == null) {
            agencia = new JTextField("", 25);
            agencia.setSize(120, 27);
        }
        return agencia;
    }

    public JTextField getConta() {
        if (conta == null) {
            conta = new JTextField("", 5);
            conta.setSize(120, 27);
        }
        return conta;
    }

    public JTextField getNome() {
        if (nome == null) {
            nome = new JTextField("", 25);
            nome.setSize(120, 27);
        }
        return nome;
    }

    public static void main(String[] args) {
        new JfmReservas().setVisible(true);
    }

    public void carregaReservas() {
        String s = saldo.getText().replaceAll("\\.", "").replaceAll("\\,", ".");
        String l = limite.getText().replaceAll("\\.", "").replaceAll("\\,", ".");
        reserva.setSaldo(Float.parseFloat(s.equals("") ? "0.0" : s));
        reserva.setNumConta(conta.getText());
        reserva.setNomeBanco(nome.getText());
        reserva.setLimite(Float.parseFloat(l.equals("") ? "0.0" : l));
        reserva.setNumAgencia(agencia.getText());
    }

    public void descarregaReservas() {
        saldo.setText(formatoDecimal.format(reserva.getSaldo()));
        conta.setText((reserva.getNumConta()));
        nome.setText((reserva.getNomeBanco()));
        limite.setText(formatoDecimal.format(reserva.getLimite()));
        agencia.setText(reserva.getNumAgencia());
    }

    public void limparTela() {
        saldo.setText("");
        conta.setText("");
        nome.setText("");
        limite.setText("");
        agencia.setText("");
    }

    public boolean ValidaCampos() {
        String msg = "Você deve preencher os seguintes campos : ";
        if (reserva.getNomeBanco().equals("")) {
            msg += " Nome ";
        }
        if (reserva.getSaldo() == 0) {
            msg += " Saldo ";
        }
        if (msg.equals("Você deve preencher os seguintes campos : ")) {
            return true;
        } else {
            JOptionPane.showMessageDialog(null, msg);
            return false;
        }


    }
}
